<?php
namespace FastPHP\Library;

class Response
{
    protected $headers = [];
    protected $code = 200;
    protected $contentType = 'text/html; charset=utf-8';

    // 设置响应状态码
    public function code($code)
    {
        $this->code = $code;
        return $this;
    }

    // 设置响应头
    public function header($name, $value)
    {
        $this->headers[$name] = $value;
        return $this;
    }

    // 设置内容类型
    public function contentType($type)
    {
        $this->contentType = $type;
        return $this;
    }

    // 发送响应内容
    public function send($content)
    {
        http_response_code($this->code);
        header('Content-Type: ' . $this->contentType);
        foreach ($this->headers as $k => $v) {
            header("$k: $v");
        }
        echo $content;
        exit;
    }

    // 发送JSON响应
    public function json($data)
    {
        $this->contentType('application/json; charset=utf-8');
        $this->send(json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    // 发送HTML响应
    public function html($html)
    {
        $this->contentType('text/html; charset=utf-8');
        $this->send($html);
    }

    // 重定向
    public function redirect($url, $code = 302)
    {
        http_response_code($code);
        header('Location: ' . $url);
        exit;
    }

    // 文件下载
    public function download($file, $name = null)
    {
        if (!file_exists($file)) {
            $this->code(404)->send('File not found');
        }
        if ($name === null) {
            $name = basename($file);
        }
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $name . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
} 